﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using KTXD.Entities;
using KTXD.Data;

namespace UserKTXD.DCTEDU_
{
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpCookie cookie = Request.Cookies.Get("NguoiDung");
            if (Request.Cookies["NguoiDung"] != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1d);
                Response.Cookies.Add(cookie);
            }
            Session.Clear();
            FormsAuthentication.SignOut();
        }

        protected void cmdDangNhap_Click(object sender, ImageClickEventArgs e)
        {
            string strUserName = Common.StandardString(UserName.Text);
            string strPassWord = Common.StandardString(Password.Text);
            string strUserCode = strUserName + strPassWord;
            strPassWord = Common.EncryptMD5(strPassWord);
            strUserCode = Common.EncryptMD5(strUserCode);
            DoLogin(strUserName, strPassWord, strUserCode);
        }

        public void DoLogin(string strUserName, string strPassword, string strUserCode)
        {
            using (NguoiDung entNguoiDung = DataRepository.NguoiDungProvider.GetByTenTruyCap(strUserName))
            {
                if (entNguoiDung == null)
                {
                    WebMessage.Show("Người dùng không tồn tại trong hệ thống, Xin vui lòng thử lại");
                    UserName.Focus();
                    return;
                }
                string CurrentPassword = entNguoiDung.MatKhau;
                string CurrentUserCode = entNguoiDung.MaTruyCap;
                string strPassWord = Common.StandardString(Password.Text);
                if (strPassword.Equals(CurrentPassword) && strUserCode.Equals(CurrentUserCode))
                {
                    string strUserInfor = string.Format("{0};{1};{2}", entNguoiDung.Id, entNguoiDung.TenTruyCap, entNguoiDung.HoTen);
                    FormsAuthentication.SetAuthCookie(strUserInfor, false);
                    Response.Redirect("~/DCTEDU_/HomeAdmin.aspx");
                }
                else
                {
                    WebMessage.Show("Mật khẩu không đúng, Xin vui lòng thử lại");
                    Password.Focus();
                    return;
                }
            }
        }
    }
}